package tvs

//功能生成绘图值

type TsVal struct {
	Ts    int64  `json:"t"`
	Value float64 `json:"v"`
}

type Period struct {
	Max *TsVal
	Min *TsVal
}

func MakeDrawValues(tvs []*TsVal, num int64) []*TsVal {
n := int64(len(tvs))
    if n <= 2 || n <= num { // 简化初始检查
        return tvs
    }
    duration := tvs[n-1].Ts - tvs[0].Ts
    if duration <= 0 { // 处理无效时间范围
        return tvs
    }

    size := (num ) / 2 // 向上取整，确保输出点数接近 num
    if size <= 0 {
        return tvs // 小 num 的 fallback
    }

    interval := duration / size  +1
	size = duration/interval +1
	beginTime := tvs[0].Ts
	periods := make([]*Period, size)

	for _, row := range tvs {
		idx := max((row.Ts-beginTime)/interval, 0)
		if idx >= size {
			break
		}
		period := periods[idx]
		if period == nil {
			period = new(Period)
			periods[idx] = period
			period.Min = row
			period.Max = row
		} else {
			if period.Min.Value > row.Value {
				period.Min = row
			}
			if period.Max.Value < row.Value {
				period.Max = row
			}
		}
	}

	var last *TsVal
	list := make([]*TsVal, num+1)
	idx := int64(0)
	for _, period := range periods {
		if idx > num{
			break
		}
		if period == nil {
			if last == nil {
				continue
			}
			ts := new(TsVal)
			*ts = *last
			ts.Ts +=interval
			last = ts
			list[idx] = ts
			idx++
			continue
		}
		if period.Max.Ts == period.Min.Ts {
			last = period.Max
			list[idx] = period.Max
			idx++
		} else {
			if period.Max.Ts < period.Min.Ts {
				last = period.Min
				list[idx] = period.Max
				idx++
				list[idx] = period.Min
				idx++
			} else {
				last = period.Max
				list[idx] = period.Min
				idx++
				list[idx] = period.Max
				idx++
			}
		}
	}

	if list[idx-1].Ts != tvs[n-1].Ts{
		list[idx] = tvs[n-1]
		idx ++
	}
	return list[:idx]
}
